package se19team1e.gui.awt;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JOptionPane;

import se19team1e.controller.Application;
import se19team1e.controller.DeleteJobAdvertController;
import se19team1e.controller.JobAdvertSearchController;
import se19team1e.controller.UpdateJobAdvertController;
import se19team1e.controller.ViewJobResponseResultController;
import se19team1e.controller.ViewJobAdvertController;
import se19team1e.controller.WithdrawJobAdvertController;
import se19team1e.entity.JobAdvertDTO;
import se19team1e.exception.DataAccessException;
import se19team1e.gui.JobAdvertSearchForm;
import se19team1e.gui.MessageBoxHelper;
import se19team1e.util.Constants;
import se19team1e.util.ReflectionUtils;

/**
 * 
 * A GUI form that allows the advertiser to search job adverts
 * 
 * @author Arun Manivannan
 * 
 */
@SuppressWarnings("serial")
public class AWTJobAdvertSearchForm extends AWTBaseScreen implements JobAdvertSearchForm {

	/**
	 * A reference to the current owning controller of this form.
	 */
	private JobAdvertSearchController controller;

	/**
	 * The job advert input panel.
	 */
	private GenericSearchPanel jobAdvertSearchPanel;

	/**
	 * Constructs a search job advert form, initializing with the application
	 * instance.
	 * 
	 * @param application
	 *            Reference to the current application instance.
	 */
	@SuppressWarnings("deprecation")
	public AWTJobAdvertSearchForm(Application application) {

		super(application);
		getContentPane().setLayout(new BorderLayout(0, 0));

		Vector<String> columnHeader = ReflectionUtils
				.getFields(new JobAdvertDTO());
		Vector<Vector> columnData = ReflectionUtils
				.getEmptyColumnData(columnHeader);
		jobAdvertSearchPanel = new GenericSearchPanel(columnHeader, columnData);
		this.setTitle("Search Job Adverts");

		getContentPane().add(jobAdvertSearchPanel);

        jobAdvertSearchPanel.getSubmitButton().addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent event) {
                   if (jobAdvertSearchPanel.getTxtSearchInput().getText()!=null){
                       
                       Vector<String> columnHeader=null;
                       try {
                           columnHeader = controller.getFields();
                       } catch (DataAccessException e1) {
                           e1.printStackTrace();
                       }
                       Vector<Vector> columnData = null;
                       
                       try {
                           List<JobAdvertDTO> searchResults = retrieve(jobAdvertSearchPanel.getTxtSearchInput().getText());
                           columnData=jobAdvertSearchPanel.convertSearchResultsToDisplayFormat(searchResults, columnHeader);
                       } catch (DataAccessException e) {
                           e.printStackTrace();
                       }
                       
                       jobAdvertSearchPanel.getTable().setModel(new GenericJTableModel(columnHeader, columnData));
                   }
                   
               }

           });
        

        jobAdvertSearchPanel.getViewButton().addActionListener(new ActionListener(){
           @Override
           public void actionPerformed(ActionEvent actionEvent) {
               
                //JTable jtable = (JTable) mouseEvent.getSource();
                int selection= jobAdvertSearchPanel.getTable().getSelectedRow();
                System.out.println("Selected row "+selection);
                //jobAdvertSearchPanel.getTable().clearSelection();
                try {
                   String jobAdvertId=(String)jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 0);
                   
                   JobAdvertDTO jobAdvertDTO = controller.retrieveById(jobAdvertId);
                   
                   ViewJobAdvertController viewController = new ViewJobAdvertController(getApplication());
                   viewController.initialize(jobAdvertDTO);
                   
               } catch (Exception e) {
                   JOptionPane.showMessageDialog(null, Constants.ERR_SELECT_A_ROW, "Info", JOptionPane.INFORMATION_MESSAGE);
                   e.printStackTrace();
               }   
           }
        });
        
        jobAdvertSearchPanel.getEditButton().addActionListener(new ActionListener(){

           @Override
           public void actionPerformed(ActionEvent actionEvent) {
               
                //JTable jtable = (JTable) mouseEvent.getSource();
                int selection= jobAdvertSearchPanel.getTable().getSelectedRow();
                System.out.println("Selected row "+selection);
                //jobAdvertSearchPanel.getTable().clearSelection();
                try {
                    System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Selected Advert id "+jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 0));
                   /*System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Selected Advert id "+jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 11));
                   System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Selected Advert id "+jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 12));*/
                   
                   String jobAdvertId=(String)jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 0);
                   
                   JobAdvertDTO jobAdvertDTO = controller.retrieveById(jobAdvertId);
                   
                   UpdateJobAdvertController updateController=new UpdateJobAdvertController(getApplication());
                   updateController.initialize(jobAdvertDTO);
                   
               } catch (Exception e) {
                   JOptionPane.showMessageDialog(null, Constants.ERR_SELECT_A_ROW, "Info", JOptionPane.INFORMATION_MESSAGE);
                   e.printStackTrace();
               }
               
           }
            
            
        });
        
        jobAdvertSearchPanel.getDeleteButton().addActionListener(new ActionListener(){
           @Override
           public void actionPerformed(ActionEvent actionEvent) {
               
                //JTable jtable = (JTable) mouseEvent.getSource();
                int selection= jobAdvertSearchPanel.getTable().getSelectedRow();
                System.out.println("Selected row "+selection);
                //jobAdvertSearchPanel.getTable().clearSelection();
                try {
                   String jobAdvertId=(String)jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 0);
                   
                   JobAdvertDTO jobAdvertDTO = controller.retrieveById(jobAdvertId);
                   
                   DeleteJobAdvertController deleteController = new DeleteJobAdvertController(getApplication());
                   deleteController.initialize(jobAdvertDTO);
                   
               } catch (Exception e) {
                   JOptionPane.showMessageDialog(null, Constants.ERR_SELECT_A_ROW, "Info", JOptionPane.INFORMATION_MESSAGE);
                   e.printStackTrace();
               }   
           }
        });

        jobAdvertSearchPanel.getWithdrawButton().addActionListener(new ActionListener(){
           @Override
           public void actionPerformed(ActionEvent actionEvent) {
                int selection= jobAdvertSearchPanel.getTable().getSelectedRow();
                try {
                   String jobAdvertId=(String)jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 0);
                   
                   WithdrawJobAdvertController withdrawController = new WithdrawJobAdvertController(getApplication());
                   withdrawController.initialize( jobAdvertId );
                   
               } catch (Exception e) {
                   JOptionPane.showMessageDialog(null, Constants.ERR_SELECT_A_ROW, "Info", JOptionPane.INFORMATION_MESSAGE);
                   e.printStackTrace();
               }   
           }
        });
        
        jobAdvertSearchPanel.getViewJobResponseButton().addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                
                 //JTable jtable = (JTable) mouseEvent.getSource();
                 int selection= jobAdvertSearchPanel.getTable().getSelectedRow();
                 System.out.println("Selected row "+selection);
                 //jobAdvertSearchPanel.getTable().clearSelection();
                 try {
                     System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Selected Advert id "+jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 0));
                    /*System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Selected Advert id "+jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 11));
                    System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Selected Advert id "+jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 12));*/
                    
                    String jobAdvertId=(String)jobAdvertSearchPanel.getTable().getModel().getValueAt(selection, 0);
                    
                    ViewJobResponseResultController controller=new ViewJobResponseResultController(getApplication());
                    controller.initialize(jobAdvertId);
                    
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, Constants.ERR_SELECT_A_ROW, "Info", JOptionPane.INFORMATION_MESSAGE);
                    e.printStackTrace();
                }
                
            }
             
             
         });
        
		// pack the layout
		this.pack();

		// hide the frame
		this.hide();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see se19team1e.gui.CreateJobAdvertForm#initialize(se19team1e.controller.
	 * CreateJobAdvertController, java.util.List, java.util.List)
	 */
	@Override
	public void initialize(JobAdvertSearchController controller) {
		this.controller = controller;
		
		// clear results
		Vector<String> columnHeader = ReflectionUtils.getFields(new JobAdvertDTO());
		Vector<Vector> columnData = ReflectionUtils.getEmptyColumnData(columnHeader);
		
		jobAdvertSearchPanel.getTable().setModel(new GenericJTableModel(columnHeader, columnData));
	}

	/**
	 * Triggers a creation of the current entered job advert info.
	 * 
	 * @throws DataAccessException
	 */
	public List<JobAdvertDTO> retrieve(String criteria) throws DataAccessException {
    	List<JobAdvertDTO> jobAdvertDTOs=new ArrayList<JobAdvertDTO>();
        // validate first
        if ( !this.validateInput() ) {
            // failure, return all the jobAdvertDTOs
        	return controller.retrieveAll();
            //return jobAdvertDTOs;
        }
        
        // delegate to controller
        jobAdvertDTOs = this.controller.retrieveByCriteria(criteria);
        
        return jobAdvertDTOs;
    }

	/**
	 * ValidateInput is used to check if the input to the Job Advert Search
	 * Panel is valid
	 * 
	 * @return boolean
	 */
	private boolean validateInput() {
		return this.jobAdvertSearchPanel.validateInput(new MessageBoxHelper(
				this.getApplication()));
	}

	/**
	 * This function in AWT jobadvert Search form will update available actions
	 * and overrides super function that Enable/disable buttons/menu of this
	 * screen.
	 */
	@Override
	public void updateAvailableActions() {
        this.updateAvailableMenuActions();

        boolean isAdvertiser = this.getApplication().getCurrentAdvertiser() != null;
        
        // always searchable
        this.jobAdvertSearchPanel.getSubmitButton().setEnabled( true );
        
        // always viewable
        this.jobAdvertSearchPanel.getViewButton().setEnabled( true );
        
     // enable actions if current logged in account is an advertiser
		this.jobAdvertSearchPanel.getViewJobResponseButton().setEnabled(isAdvertiser);
		this.jobAdvertSearchPanel.getEditButton().setEnabled(isAdvertiser);
        this.jobAdvertSearchPanel.getDeleteButton().setEnabled( isAdvertiser );
        this.jobAdvertSearchPanel.getWithdrawButton().setEnabled( isAdvertiser );

	}

}
